"""
akile签到

支持多用户运行

入口：https://akile.io/register?aff_code=f4cb5705-e1d9-435a-9db4-5d1df9d790a0

多用户用&或者@隔开
例如：邮箱1#密码1&邮箱2#密码2
export akile="username#password"

cron: 55 8 * * *
const $ = new Env("akile");
"""
import requests
import re
import os
import time
import json
from datetime import datetime
import cloudscraper
import io
import logging
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from notify import send

# 创建 StringIO 对象
log_stream = io.StringIO()

# 配置 logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)

# 创建控制台 Handler
console_handler = logging.StreamHandler()
console_handler.setFormatter(
    logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))

# 创建 StringIO Handler
stream_handler = logging.StreamHandler(log_stream)
# stream_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))

# 将两个 Handler 添加到 logger
logger.addHandler(console_handler)
logger.addHandler(stream_handler)

#分割变量
if 'akile' in os.environ:
    akile = re.split("&",os.environ.get("akile"))
    logger.info(f"查找到{len(akile)}个账号")
else:
    akile =['']
    print('akile')


def getToken(username, password):
    
    # 创建一个 cloudscraper 实例（它会自动处理 cookies 和 challenge）
    scraper = cloudscraper.create_scraper()

    # 登录的目标 URL
    url = 'https://api.akile.io/api/v1/user/login'

    # 登录请求的数据（替换为你实际的账号密码字段）
    data = {"email": username, "password": password, "token": "", "verifyCode": ""}

    # 请求头（可选，但更真实）
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
    }
    
    # 发送 POST 请求（绕过 Cloudflare）
    response = scraper.post(url, json=data, headers=headers)
    if response.status_code == 200:
        data = response.json()
        logger.info((f"账号：{username}{data['status_msg']}"))
        token = data["data"]["token"]
    return token


def get_user(ck):
    username = re.split("#",ck)[0]
    password = re.split("#",ck)[1]
    return username,password


def qd(token):
    # 创建一个 cloudscraper 实例（它会自动处理 cookies 和 challenge）
    
    scraper = cloudscraper.create_scraper()
    
    # 登录的目标 URL
    url = 'https://api.akile.io/api/v1/user/Checkin'

    # 请求头（可选，但更真实）
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36 Edg/137.0.0.0",
        "authorization": token
    }
    
    # 发送 GET 请求（绕过 Cloudflare）
    response = scraper.get(url, headers=headers)
    if response.status_code == 200:
        data = response.json()
        logger.info((f"{data['status_msg']}"))
    return data

def ak_coin(token):
    url = 'https://api.akile.io/api/v1/user/index'
    scraper = cloudscraper.create_scraper()
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36 Edg/137.0.0.0",
        "authorization": token
    }
    response = scraper.get(url, headers=headers)
    if response.status_code == 200:
        data = response.json()
        logger.info((f"{data['status_msg']}"))
        coin = data['data']['ak_coin']
        logger.info(f"当前ak币: {coin}")
    return coin

def main():
    z = 1
    for ck in akile:
        try:
            logger.info(f'登录第{z}个账号')
            logger.info('----------------------')
            username,password = get_user(ck)
            token = getToken(username,password)
            qd(token)
            ak_coin(token)
            logger.info('----------------------')
            z = z + 1
        except Exception as e:
            logger.info('未知错误')

if __name__ == '__main__':
    try:
        main()
    except Exception as e:
        logger.info('未知错误')
    try:
        log_contents = log_stream.getvalue()
        send("akile：", log_contents)
    except Exception as e:
        logger.info('小错误')